package com.roc.web.action.profitShare;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.AuditingItem;
import com.roc.pojo.Operators;
import com.roc.pojo.OrgBean;
import com.roc.pojo.ProfitShareDetail;
import com.roc.service.IAgentService;
import com.roc.service.IExcelService;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;
import com.roc.service.IProfitShareService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.agent.IAgentInfoService;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.OperatorsStatus;
import com.roc.util.constant.Role;
import com.roc.util.constant.SexStatus;

/**
 * 分润明细查询
 * 
 * @author zx
 * 
 */

@Component
@Scope("prototype")
@Namespace("/profitShareDetail")
public class ProfitShareQueryDetailAction extends PaginationBaseAction {

	private Logger logger = LogManager
			.getLogger(ProfitShareQueryDetailAction.class);

	private ProfitShareQueryDetailSearchCondition searchCondition;

	private Operators merchant;

	private AuditingItem auditing;

	private List<OrgBean> orgList = new ArrayList<OrgBean>();

	private List<Operators> operatorsList = new ArrayList<Operators>();

	private String code;

	private InputStream excelFile;

	private String excelName;

	private Operators agent;

	@Autowired
	IorgService orgService;

	@Autowired
	IPagenitionService pagenitionService;

	@Autowired
	IMerchantServices merchantServices;

	@Autowired
	IPowerInfoService powerInfoService;

	@Autowired
	IAgentInfoService agentInfoService;
	@Autowired
	IMerchantServices merinfoService;
	@Autowired
	IAgentService agentService;

	@Autowired
	IProfitShareService profitShareService;

	@Autowired
	IExcelService excelService;

	@Action(value = "profitShareDetailJsp", results = { @Result(name = "success", location = "/pages/profit_share/profit_share_detail_query.jsp") })
	public String queryProfitShareDetailJspAction() throws Exception {

		try {
			org();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
			addActionError(e.getMessage());
			return ERROR;
		}

		return SUCCESS;
	}

	@Action(value = "queryProfitShareDetail", results = { @Result(name = "success", location = "/pages/profit_share/profit_share_detail_query.jsp") })
	// 查询分润明细
	public String queryProfitShareDetailAction() throws Exception {

		if (searchCondition == null) {
			searchCondition = (ProfitShareQueryDetailSearchCondition) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new ProfitShareQueryDetailSearchCondition();
			}
		}
		try {

			org();

			int rows = pagenitionService.countSQL(searchCondition);
			searchRsList = pagenitionService.findAllSQL(searchCondition,
					calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);

			List<ProfitShareDetail> proList = new ArrayList<ProfitShareDetail>();
			if (searchRsList.size() > 0 && searchRsList != null) {

				Iterator iterator = searchRsList.iterator();
				while (iterator.hasNext()) {
					Object[] obj = (Object[]) iterator.next();
					ProfitShareDetail msb = new ProfitShareDetail();
					msb.setAgentId(Constance.Null2EmptyTrim(obj[0]));
					msb.setMid(Constance.Null2EmptyTrim(obj[1]));
					msb.setMerName(Constance.Null2EmptyTrim(obj[2]));
					msb.setCommMode(Constance.Null2EmptyTrim(obj[3]));
					msb.setCommRate(Constance.Null2EmptyTrim(obj[4]));
					msb.setCommAmt(Constance.Null2EmptyTrim(obj[5]));
					msb.setMcc(Constance.Null2EmptyTrim(obj[6]));
					msb.setAccountNo(Constance.Null2EmptyTrim(obj[7]));
					msb.setRealName(Constance.Null2EmptyTrim(obj[8]));
					msb.setRealNameUp(Constance.Null2EmptyTrim(obj[9]));
					msb.setMccType(Constance.Null2EmptyTrim(obj[10]));
					msb.setMerfee(Constance.Null2EmptyTrim(obj[11]));
					msb.setAmount(Constance.Null2EmptyTrim(obj[12]));
					msb.setTermid(Constance.Null2EmptyTrim(obj[13]));
					msb.setEtsdate(Constance.Null2EmptyTrim(obj[14]));
					msb.setEtstime(Constance.Null2EmptyTrim(obj[15]));
					msb.setAccount(Constance.Null2EmptyTrim(obj[16]));
					msb.setEtstrancode(Constance.Null2EmptyTrim(obj[17]));
					msb.setRespcode(Constance.Null2EmptyTrim(obj[18]));
					msb.setReversal(Constance.Null2EmptyTrim(obj[19]));
					msb.setMaxFee(Constance.Null2EmptyTrim(obj[20]));
					msb.setProfitFee(Constance.Null2EmptyTrim(obj[21]));
					msb.setProfitSettleRate(Constance.Null2EmptyTrim(obj[22]));
					msb.setMccTypeName(Constance.Null2EmptyTrim(obj[23]));
					msb.setFenrunAmt(new BigDecimal(Constance
							.Null2EmptyTrim(obj[24])));

					proList.add(msb);
				}

			}

			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, proList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
			addActionError(e.getMessage());
			return ERROR;
		}

		return SUCCESS;
	}

	// 查询机构
	public void org() throws Exception {
		Operators logingOperators = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);
		orgList = orgService.listOrgs(logingOperators);
		getRequest().setAttribute("orgList", orgList);

		// 加载角色类型
		Map roleMap = new HashMap();
		if (logingOperators.getRoleType().equals(Role.AGENT.getCode())) {
			roleMap.put(Role.AGENT.getCode(), Role.AGENT.getName());
		} else {
			roleMap.put(Role.O_MANAGER.getCode(), Role.O_MANAGER.getName());
			roleMap.put(Role.AGENT.getCode(), Role.AGENT.getName());
		}
		getRequest().setAttribute("roleMap", roleMap);

	}

	protected void agentTheListSpecially(List<Object> list) {
		List<Object> tempList = new ArrayList<Object>();
		for (Object obj : list) {
			Operators temp = (Operators) obj;
			for (OrgBean bean : orgList) {
				if (temp.getOrgCode().equals(bean.getOrg_code())) {
					temp.setOrgName(bean.getOrg_name());
				}
			}

			for (Operators opera : operatorsList) {
				if (opera.getId() == temp.getSuperiorId()) {
					temp.setSuperiorName(opera.getRealName());
				}
			}
			temp.setSex(SexStatus.valueOfCode(temp.getSex()).getName());
			temp.setRoleName(Role.valueOfCode(temp.getRoleType()).getName());
			temp.setStatus(OperatorsStatus.valueOfCode(temp.getStatus())
					.getName());
			tempList.add(temp);
		}
		searchRsList = tempList;

	}

	// 导出excel
	@Action(value = "excelProFitShareDetail", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xls", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/error.jsp") })
	public String excelProFitShareDetail() throws Exception {

		ByteArrayOutputStream output = new ByteArrayOutputStream();
		try {


			org();

			if (searchCondition == null) {
				searchCondition = (ProfitShareQueryDetailSearchCondition) getSearchConditionFromSession();
				if (searchCondition == null) {
					searchCondition = new ProfitShareQueryDetailSearchCondition();
				}
			}

			int rows = pagenitionService.countSQL(searchCondition);

			searchRsList = pagenitionService.findAllSQL(searchCondition, 0,
					rows);
			
			Operators agentOp = merchantServices.findMerchantByNo(searchCondition.getAccountNo()); 

			HSSFWorkbook work = excelService.proFitShareDetailExcel(
					searchRsList, searchCondition.getMinDate(), searchCondition
							.getMaxDate(),agentOp);

			work.write(output);

			byte[] ba = output.toByteArray();
			excelFile = new ByteArrayInputStream(ba);
			output.flush();
			output.close();

		} catch (Exception e) {
			logger.info("######导出分润明细失败######");
			addActionError(e.getMessage());
			return ERROR;
		} finally {
			closeOutPut(output);
		}

		return SUCCESS;
	}

	private void closeOutPut(ByteArrayOutputStream output)
			throws ServiceException {

		try {
			if (output != null) {
				output.flush();
				output.close();
			}
		} catch (IOException e) {
			logger.error("########导出Excel关闭流失败######", e);
			throw new ServiceException("导出Excel关闭流失败！");
		}
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE + "";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSession()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (ProfitShareQueryDetailSearchCondition) getSession()
				.getAttribute(SEARCH_SESSION_PROFIT_SHARE_DETAIL_QUERY);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSubClass()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.roc.page.PaginationBaseAction#setSearchConditionToSubClass(com.roc
	 * .page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.roc.page.PaginationBaseAction#setSearchToConditionSession(com.roc
	 * .page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_PROFIT_SHARE_DETAIL_QUERY,
				searchCondition);
	}

	public Operators getMerchant() {
		return merchant;
	}

	public void setMerchant(Operators merchant) {
		this.merchant = merchant;
	}

	public ProfitShareQueryDetailSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(
			ProfitShareQueryDetailSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public AuditingItem getAuditing() {
		return auditing;
	}

	public void setAuditing(AuditingItem auditing) {
		this.auditing = auditing;
	}

	public List<OrgBean> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<OrgBean> orgList) {
		this.orgList = orgList;
	}

	public List<Operators> getOperatorsList() {
		return operatorsList;
	}

	public void setOperatorsList(List<Operators> operatorsList) {
		this.operatorsList = operatorsList;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public Operators getAgent() {
		return agent;
	}

	public void setAgent(Operators agent) {
		this.agent = agent;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public String getExcelName() {
		return excelName;
	}

	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}

}
